import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

public class ToExcel {
    static MongoClient mongoClient = new MongoClient("192.168.1.173", 27017);
    static MongoDatabase mDatabase = mongoClient.getDatabase("巨潮网络");
    static MongoCollection collection = mDatabase.getCollection("沪市_会计差错");
    static Logger logger = LoggerFactory.getLogger(ToExcel.class);

    public static void main(String[] args) throws IOException {
        FindIterable<Document> documents = collection.find();
        Set<String> set_list = new LinkedHashSet<>();
        for (Document document : documents){
            set_list.addAll(document.keySet());
        }

        Workbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        Row row = sheet.createRow(0);
        int index = 0;
        int n = set_list.size();
        for (String key : set_list)
            row.createCell(index++).setCellValue(key);

        int rownum = 1;
        int count = 0;
        for (Document document : documents) {
            int cellnum = 0;

            count++;
            Row row1 = sheet.createRow(rownum++);
            for (String key : set_list){
                try {
                    row1.createCell(cellnum++).setCellValue(document.get(key).toString());
                }
                catch (Exception e){
                    row1.createCell(cellnum++).setCellValue("");
                }

            }

            System.out.println("正在写入------------------------------");
        }

        workbook.write(new FileOutputStream("D:\\测试临时文件\\nianhao_2020.xlsx"));
        System.out.println("写去excel完毕*--------------------");
        System.out.println("条目数量：" + count);
    }


}
